<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;

use DB;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class ShoppingCarController extends Controller
{
    public function shoppingCar(Request $request)
    {
    	session_start();
       //遍历商品数据
    	$num=$request->input('goods_num');
    	$gid=$request->input('gid');

    	//dd($num);
        $gresult=DB::table('goods')
        ->where('gid',$gid)
        ->get();
        //遍历前台导航数据
        $cresult=DB::table('category')
        ->get();

        if(!$gresult){
        	return back()->withInput();
        }
        $gresult[0]->nnum =(int)$num;
        
        //存入SESSION操作
        if(isset($_SESSION['shop'][$gresult[0]->gid])){
        	$_SESSION['shop'][$gresult[0]->gid]->nnum+=(int)$num;
        }else{
        	$_SESSION['shop'][$gresult[0]->gid] = $gresult[0];
        }
        
        //dd($_SESSION['shop'][$gresult[0]->gid]);
        //dd($_SESSION['shop']);
        //返回首页试图模板并分配数据
       return view('/Home/shoppingCar/ShoppingCar',['cresult'=>$cresult,'gresult'=>$gresult]);
    }

    public function getshoppingCar()
    {
    	session_start();
    	$gresult=DB::table('goods')
        ->get();
        //遍历前台导航数据
        $cresult=DB::table('category')
        ->get();
    	if(isset($_SESSION['shop'])){
    		return view('/Home/shoppingCar/ShoppingCar',['cresult'=>$cresult,'gresult'=>$gresult]);
    	}else{
    		return view('/Home/shoppingCar/ShoppingCar',['cresult'=>$cresult,'gresult'=>$gresult]);
    	}
    	
    }

    //删除单个session
    public function delshopping($id)
    {
    	session_start();
    	// dd($_SESSION['shop']);
        if($id==0){
            unset($_SESSION['shop']);    
        }else{
           unset($_SESSION['shop'][$id]);
        }
    	return redirect('/getshoppingCar');
    }
}
